
Page({

  /**
   * 页面的初始数据
   */
  data: {
      info:{},
      oldid:"",
      loading:false,
      name:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    this.setData({
      oldid:options.oidid
    })
    this.getInfo();
  },
  getInfo(){
    wx.cloud.callFunction({
      name:"Oldman",
      data:{
        type:"selectById",
        id:this.data.oldid
      }
    }).then(res=>{
      this.setData({
        name:res.result.data.name
      })
    })
  },
  submit(){

      if(Object.keys(this.data.info).length<7){
            wx.showToast({
              title: '请填写完整',
              icon:"error"
            })
            return
      }
        
      wx.cloud.callFunction({
        name:"health",
        data:{
          type:"count",
          id:this.data.oldid
        }
      }).then(res=>{
        if(res.result.total>0){
            this.submitData();
        }else{
          this.addData();
        }
      })
  
  },
checkHealthValues(healthData) {
  const date = new Date();
  var now=this.formatDate(date); // 输出: "2023-10-20 12:34:56"
    const { acid, glucose, lipid, pressure, temperature, heart } = healthData;

    let anomalies = [];

    // 尿酸异常检查（单位：μmol/L）
    if (acid < 149 || acid > 416) {
        anomalies.push({ 
          message: "尿酸异常", 
          value: `${acid} μmol/L`,
          pid:this.data.oldid,
          time:now,
          name:this.data.name
        });
    }

    // 血糖异常检查（空腹，单位：mmol/L）
    if (glucose < 3.9 || glucose > 6.1) {
        anomalies.push({ message: "血糖异常", value: `${glucose} mmol/L` ,pid:this.data.oldid,
        time:now,
        name:this.data.name});
    }

    // 血脂异常检查（总胆固醇，单位：mmol/L）
    if (lipid >= 5.2) {
        anomalies.push({ message: "血脂异常", value: `${lipid} mmol/L` ,pid:this.data.oldid,
        time:now,
        name:this.data.name});
    }

    // 血压异常检查（单位：mmHg）
    if (pressure.systolic < 90 || pressure.systolic > 120 || pressure.diastolic < 60 || pressure.diastolic > 80) {
        anomalies.push({ message: "血压异常", value: `${pressure.systolic}/${pressure.diastolic} mmHg`,pid:this.data.oldid,   time:now,
          name:this.data.name });
    }

    // 体温异常检查（单位：°C）
    if (temperature < 36.0 || temperature > 37.2) {
        anomalies.push({ message: "体温异常", value: `${temperature} °C` ,pid:this.data.oldid,   time:now,
        name:this.data.name});
    }

    // 心率异常检查（单位：次/分钟）
    if (heart < 60 || heart > 100) {
        anomalies.push({ message: "心率异常", value: `${heart} 次/分钟`,pid:this.data.oldid,   time:now,
        name:this.data.name });
    }

    return anomalies;
},

  addData(){
      var arry=this.checkHealthValues(this.data.info)
      console.log(arry)
      if(arry.length>0){
        wx.cloud.callFunction({
          name:"warning",
          data:{
            type:"add",
            array: arry        
          }
        })
      }
    this.setData({
      loading:true
    })
    const date = new Date();
    var now=this.formatDate(date); // 输出: "2023-10-20 12:34:56"
      wx.cloud.callFunction({
        name:"health",
        data:{
          type:"add",
          acid:this.data.info.acid,
          glucose:this.data.info.glucose,
          lipid:this.data.info.lipid,
          weight:this.data.info.weight,
          pressure:this.data.info.pressure,
          temperature:this.data.info.temperature,
          heart:this.data.info.heart,
          oldid:this.data.oldid,
          time:now
        }
      }).then(res=>{
        this.setData({
          loading:false
        })
        setTimeout(() => {
          wx.showToast({
            title: '上传成功',
          
          })
        }, 1000);
        var pages = getCurrentPages();   //当前页面

        var prevPage = pages[pages.length - 2];   //上一页面
        
        prevPage.setData({
               //直接给上一个页面赋值
               ist: true,        
        });
        wx.navigateBack({
             //返回
             delta: 1
        })
      })
  },
  submitData(){
    var arry=this.checkHealthValues(this.data.info)
    console.log(arry)
    if(arry.length>0){
      wx.cloud.callFunction({
        name:"warning",
        data:{
          type:"add",
          array: arry        
        }
      })
    }
    this.setData({
      loading:true
    })
  const date = new Date();
    var now=this.formatDate(date); // 输出: "2023-10-20 12:34:56"
      wx.cloud.callFunction({
        name:"health",
        data:{
          type:"update",
          acid:this.data.info.acid,
          glucose:this.data.info.glucose,
          lipid:this.data.info.lipid,
          weight:this.data.info.weight,
          pressure:this.data.info.pressure,
          temperature:this.data.info.temperature,
          heart:this.data.info.heart,
          oldid:this.data.oldid,
          time:now
        }
      }).then(res=>{
        this.setData({
          loading:false
        })
        setTimeout(() => {
          wx.showToast({
            title: '上传成功',
          
          })
        }, 1000);
        var pages = getCurrentPages();   //当前页面

        var prevPage = pages[pages.length - 2];   //上一页面
        
        prevPage.setData({
               //直接给上一个页面赋值
               ist: true,        
        });

        console.log(123)

        wx.navigateBack({
             //返回
             delta: 1
        })
      })
  },

  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},
  onChange(e){
    const param = e.currentTarget.dataset.name; //字段名 
    const value = e.detail; //值 
    const key=`info.${param}`;
    this.setData({
      [key]:value
    })
  }

  
})